package com.googlecode.stateless4j.conversion;

import com.googlecode.stateless4j.validation.ArgumentValidator;

public class ParameterConversion
{
    private static final String tooManyParameters = "Trop de parametres";
    private static final String argOfTypeRequiredInPosition = "ArgOfTypeRequiredInPosition";
    private static final String wrongArgType = "WrongArgType";

    private static Object unpack(Object[] args, Class<?> argType, int index)
    {
        ArgumentValidator.argumentNotNull(args, "args");

        if (args.length <= index)
            throw new IllegalArgumentException(String.format(argOfTypeRequiredInPosition, argType, index));

        Object arg = args[index];

        if (arg != null && !argType.isAssignableFrom(arg.getClass()))
            throw new IllegalArgumentException(String.format(wrongArgType, index, arg.getClass(), argType));

        return arg;
    }

    public static void validate(Object[] args, Class<?>[] expected)
    {
        if (args.length > expected.length)
            throw new IllegalArgumentException(String.format(tooManyParameters, expected.length, args.length));

        for (int i = 0; i < expected.length; ++i)
            unpack(args, expected[i], i);
    }
}
